package com.qingniao.hb.web.servlet;

import com.alibaba.druid.util.StringUtils;
import com.qingniao.hb.entity.Books;
import com.qingniao.hb.service.BookService;
import com.qingniao.hb.service.impl.BookServiceImpl;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

/**
 * @author xlzhang
 * @date 2023/4/18 10:32
 */
@Slf4j
@MultipartConfig
@WebServlet("/books/*")
public class BookServlet extends BaseServlet{

    private final BookService bookService = new BookServiceImpl();

    /**
     * 删除图书功能
     */
    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收要删除的图书id
        //final String bid = request.getParameter("bid");
        //boolean res = bookService.delBook(bid);
        final String[] bids = request.getParameterValues("bid");
        System.out.println("bids = " + Arrays.toString(bids));
        boolean res = bookService.deleteBatch(bids);
        response.sendRedirect(getServletContext().getContextPath() + "/bookManager.html");
    }

    /**
     * 添加图书功能
     */
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收参数，封装为一个books对象
        final Books books = getBooks(request);
        // 将对象传递给数据保存   service  - dao
        boolean res = bookService.addBook(books);
        response.sendRedirect(getServletContext().getContextPath() + "/bookManager.html");
    }

    /**
     * 修改图书功能
     */
    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 封装数据到对象中
        final Books books = getBooks(request);
        // 将对象传递给数据保存   service  - dao
        boolean res = bookService.updateBook(books);
        response.sendRedirect(getServletContext().getContextPath() + "/bookManager.html");
    }

    /**
     * 封装请求参数
     * @param request
     * @return
     */
    private Books getBooks(HttpServletRequest request) throws ServletException, IOException {
        // 接收参数，封装为一个books对象
        final Books books = new Books();
        // 接收图书数据
        try {
            books.setId(Integer.parseInt(request.getParameter("id")));
        } catch (NumberFormatException e) {
            log.debug("--输入的id异常");
        }
        books.setTitle(request.getParameter("title"));
        books.setAuthor(request.getParameter("author"));
        books.setPrice(Double.parseDouble(request.getParameter("price")));
        books.setStock(Integer.parseInt(request.getParameter("stock")));
        // 专门处理上传的文件
        saveFile(request,books);

        return books;
    }

    /**
     * 封装的处理上传文件的方法
     * @param request
     * @param books
     * @return
     */
    private void saveFile(HttpServletRequest request,Books books) throws ServletException, IOException {
        // 1. 从请求中获取封装了文件数据的Part对象
        final Part imgPart = request.getPart("img_path");
        // 2. 获取上传文件对应的名称,servlet3.1版本才有
        String fileName = imgPart.getSubmittedFileName();
        // 判断当前是否有图片上传，有才去处理
        if (!StringUtils.isEmpty(fileName)) {
            log.debug("--上传文件的名称：{}", fileName);
            // 对文件名称进行去重处理，一般处理方式就是分文件夹(年月日)或者给文件名拼接一个随机字符串(尽量保证唯一性)
            // jdk准备一个生成随机字符串的类  UUID,
            fileName = UUID.randomUUID() + "-" + fileName;
            // 先创建一个文件的保存地址路径
            // 通过servletContext获取当前项目运行的真实目录
            File realPath = new File(getServletContext().getRealPath("/static/uploads"));
            if (!realPath.exists()) {
                log.debug("--文件存储路径异常：{}", realPath);
                return;
            }
            // 拼接文件名，生成一个完整的文件保存路径
            File fileSavePath = new File(realPath, fileName);
            // 3. 保存文件
            imgPart.write(fileSavePath.getAbsolutePath());

            // 4. 获取一个保存到数据库中的地址
            books.setImg_path("static/uploads/" + fileName);
        }
    }
}
